package com.ruicar.afs.cloud.auth.validater;

import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.constant.SystemInnerConstants;
import com.ruicar.afs.cloud.common.core.security.service.AfsNoPassLoginService;
import lombok.Setter;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2RequestValidator;
import org.springframework.security.oauth2.provider.TokenRequest;

import java.util.Map;
import java.util.Set;

public class AfsOauthRequestValidator implements OAuth2RequestValidator {
    @Setter
    private AfsNoPassLoginService afsNoPassLoginService;
    @Override
    public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException {
        validateParams(authorizationRequest.getRequestParameters(),client.getScope());
        validateScope(authorizationRequest.getScope(), client.getScope());
    }

    @Override
    public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException {
        validateParams(tokenRequest.getRequestParameters(),client.getScope());
        validateScope(tokenRequest.getScope(), client.getScope());
    }

    private void validateParams(Map<String,String> params,Set<String> clientScopes){
        if(params.containsKey(CommonConstants.NO_PASS_LOGIN)){
            if (!clientScopes.contains(CommonConstants.NO_PASS_SCOPE)){
                throw new InvalidScopeException("客户端配置不允许免密登录");
            }
            if(!afsNoPassLoginService.validateCheckCode(params.get(CommonConstants.NO_PASS_LOGIN))){
                throw new InvalidScopeException("请求不合法");
            }
        }
    }
    private void validateScope(Set<String> requestScopes, Set<String> clientScopes) {
        if (clientScopes != null && !clientScopes.isEmpty()) {
            for (String scope : requestScopes) {
                if (!clientScopes.contains(scope)) {
                    throw new InvalidScopeException("Invalid scope: " + scope, clientScopes);
                }
            }
        }
        if (requestScopes.isEmpty()) {
            throw new InvalidScopeException("Empty scope (either the client or the user is not allowed the requested scopes)");
        }
    }
}
